import { defineStore } from "pinia";
import router from "@/router";

let modules = import.meta.glob("../../views/Pages/*.vue");

// 组成路由树
const buildDynamicRoutes = (data, parentId = 0) => {
    return data
        .filter(el => el.parentId === parentId)
        .map(el => {
            const children = buildDynamicRoutes(data, el.id);

            const newRoute = {
                path: el.path,
                name: el.name,
                meta: JSON.parse(el.meta)
            };

            if (el.component) {
                newRoute.component = modules[`../../views/Pages/${el.component}`];
            }

            if (children.length > 0) {
                newRoute.children = children;
            }

            return newRoute;
        });
};

// 动态路由
const RoutesStore = defineStore('addRoutes', {
    state: () => ({
        info: [], // 存储目录栏
        addRoutes: [] // 存储动态路由
    }),
    actions: {
        Info(data) {
            this.info = data;
        },
        AddRoutes(data) {
            try {
                const dynamicRoutes = buildDynamicRoutes(data);
                this.addRoutes = dynamicRoutes;
            } catch (error) {
                console.error(error);
                ElMessage.error('路由组建失败');
            }
        }
    },
})

export default RoutesStore;